﻿using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml.Linq;

namespace QuickLogin.Utilities
{
    public static class XmlHelper
    {
        const int TIMEOUT = 5 * 1000;
        public static readonly XNamespace xNamespace = "http://www.turbine.com/SE/GLS";
        public static string GetVal(this XElement element, string Name)
        {
            string val = string.Empty;
            try
            {
                if (element != null)
                {
                    var node = element.Element(Name);
                    if (node != null && !string.IsNullOrEmpty(node.Value))
                    {
                        return node.Value.Trim();
                    }
                }
            }
            catch (Exception e) { Trace.WriteLine(e.ToString()); }
            return val;
        }

        public static string GetValByNamespace(this XElement element, string Name)
        {
            string val = string.Empty;
            try
            {
                if (element != null)
                {
                    var node = element.Element(xNamespace + Name);
                    if (node != null && !string.IsNullOrEmpty(node.Value))
                    {
                        return node.Value.Trim();
                    }
                }
            }
            catch (Exception e) { Trace.WriteLine(e.ToString()); }
            return val;
        }
        /// <summary>
        /// 读取Response中的数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        static XDocument GetResponseData(WebRequest request)
        {
            using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
            {
                string retXml = reader.ReadToEnd();
                reader.Close();
                return XDocument.Parse(retXml);
            }
        }

        /// <summary>
        /// 设置WebRequest头
        /// </summary>
        /// <param name="header"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void SetHeaderValue(this WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }

        /// <summary>
        /// 调用地址并返回结果
        /// </summary>
        /// <param name="Uri">请求地址</param>
        /// <param name="method">请求方法GET,POST</param>
        /// <param name="ContentType"></param>
        /// <param name="RequestBody"></param>
        /// <param name="HeaderConfig"></param>
        /// <returns></returns>
        public static XDocument CallUrl(string Uri,
            RequestMethod method = RequestMethod.GET,
            string ContentType = "text/xml;charset=utf-8",
            string RequestBody = "",
            string UserAgent = "Turbine Launcher",
            Action<WebHeaderCollection> HeaderConfig = null)
        {
            //请求头
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);
            request.Method = method.ToString();
            request.ContentType = ContentType;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = TIMEOUT;
            request.UserAgent = UserAgent;
            //设置Header
            HeaderConfig?.Invoke(request.Headers);
            //写入RequestBody
            if (method == RequestMethod.POST && !string.IsNullOrEmpty(RequestBody))
            {
                //写入数据
                byte[] data = Encoding.UTF8.GetBytes(RequestBody);
                request.ContentLength = data.Length;
                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(data, 0, data.Length);
                    writer.Close();
                }
            }
            //调用请求并返回信息
            return GetResponseData(request);

        }
    }
    public enum RequestMethod
    {
        POST,
        GET
    }
}
